<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>申请更换部门</span>
      </div>
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="现有部门" prop="currentDeptName">
          <el-input v-model="form.currentDeptName" disabled placeholder="当前所在部门" />
        </el-form-item>
        <el-form-item label="目标部门" prop="targetDeptId" :rules="[{ required: true, message: '请选择目标部门', trigger: 'change' }]">
          <treeselect v-model="form.targetDeptId" :options="deptTreeOptions" :normalizer="normalizer" :disabled-branch-nodes="true"
                      placeholder="请选择目标部门" style="width: 100%" :loading="loading" :clearable="true" />
        </el-form-item>
        <el-form-item label="申请原因" prop="applyReason" :rules="[{ required: true, message: '请填写申请原因', trigger: 'blur' }]">
          <el-input v-model="form.applyReason" type="textarea" :rows="4" placeholder="请详细说明申请更换部门的原因" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">提交申请</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>


<!--      {-->
<!--      "createBy": "",-->
<!--      "createTime": "2025-11-05 15:31:37",-->
<!--      "updateBy": "",-->
<!--      "updateTime": null,-->
<!--      "remark": null,-->
<!--      "id": 1,-->
<!--      "userId": 1,-->
<!--      "currentDeptId": 103,-->
<!--      "currentDeptName": "本科研究生",-->
<!--      "targetDeptId": 123,-->
<!--      "targetDeptName": "妇产科",-->
<!--      "applyTime": "2025-11-05",-->
<!--      "approvalTime": null,-->
<!--      "approverId": null,-->
<!--      "status": 1,-->
<!--      "applyReason": "22"-->
<!--      }-->

    <!-- 申请列表 -->
    <el-card class="mt-4">
      <div slot="header" class="clearfix">
        <span>申请记录</span>
      </div>
      <el-table :data="applyList" style="width: 100%" stripe>
        <el-table-column prop="createTime" label="申请时间" min-width="180" align="center">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="currentDeptName" label="原部门" min-width="140" align="center" />
        <el-table-column prop="targetDeptName" label="目标部门" min-width="140" align="center" />
        <el-table-column prop="status" label="状态" min-width="100" align="center">
          <template slot-scope="scope">
            <el-tooltip
              v-if="scope.row.status === 3"
              :content="scope.row.reasonsRejection || '暂无驳回原因'"
              placement="top"
              effect="dark"
            >
              <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
            </el-tooltip>
            <el-tag v-else :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="approvalTime" label="审批时间" min-width="180" align="center">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.approvalTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="180" align="center" class-name="small-padding">
            <template slot-scope="scope">
                <el-button v-if="scope.row.status === 3" size="mini" type="primary" icon="el-icon-edit" @click="handleModifyAndResubmit(scope.row)">再次修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:apply:remove']">删除记录</el-button>
            </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import deptTransferApi from '@/api/system/deptTransfer'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {delApply, updateApply} from "@/api/system/apply";
import {copyObj} from "@/utils/zzDouUtils/objUtil";
import { getUserProfile } from "@/api/system/user"


export default {
  name: 'deptTransferApply',
  components: { Treeselect },
  props: {
  },
  data() {
    return {
      form: {
        currentDeptId: '',
        currentDeptName: '',
        targetDeptId: null,
        targetDeptName: '',
        applyReason: ''
      },
      deptOptions: [],
      deptTreeOptions: [],
      applyList: [],
      loading: false
    }
  },
  created() {
    this.initData();
    this.getUser();
  },

  methods: {
    initData() {
      // 初始化表单数据
      if (this.user && this.user.dept) {
        this.form.currentDeptId = this.user.dept.deptId
        this.form.currentDeptName = this.user.dept.deptName
      }
      // 获取部门列表
      this.getDeptList()
      // 获取申请历史列表
      this.getApplyList()
    },
    getDeptList() {
      deptTransferApi.getDeptList().then(response => {
        this.deptOptions = response.data
        // 转换为树形结构
        this.deptTreeOptions = this.handleTree(response.data, 'deptId')
      }).catch(error => {
        console.error('获取部门列表失败:', error)
        this.$message.error('获取部门列表失败')
      })
    },
    // 转换科室数据结构
    normalizer(node) {
      // 如果当前节点是用户所在部门，则不返回，实现禁用效果
      if (node.deptId === this.form.currentDeptId) {
        return null
      }
      // 移除空的children数组
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }
    },
    // 查找部门名称
    findDeptNameById(deptId) {
      const dept = this.deptOptions.find(item => item.deptId === deptId)
      return dept ? dept.deptName : ''
    },
    findDeptById(list, deptId) {
      // 递归查找部门
      for (let i = 0; i < list.length; i++) {
        if (list[i].deptId === deptId) {
          return list[i]
        }
        if (list[i].children && list[i].children.length > 0) {
          const found = this.findDeptById(list[i].children, deptId)
          if (found) return found
        }
      }
      return null
    },
    // 格式化日期时间为指定格式: 2025-11-5 18:31:28
    formatDateTime(dateTime) {
      if (!dateTime) return '-' // 如果时间为空，返回'-'

      const date = new Date(dateTime)
      if (isNaN(date.getTime())) return '-' // 如果不是有效日期，返回'-'

      const year = date.getFullYear()
      const month = date.getMonth() + 1 // 月份从0开始，需要+1
      const day = date.getDate()
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')

      // 月和日不加前导0，符合要求的格式
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    getApplyList() {
      deptTransferApi.getApplyList().then(response => {
        this.applyList = response.data
      }).catch(error => {
        console.error('获取申请历史失败:', error)
        this.$message.error('获取申请历史失败')
      })
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 检查是否有未完成的申请（状态为0：申请中 或 1：待审核）
          const hasPendingApply = this.applyList.some(item =>
            item.status === 0 || item.status === 1
          );

          if (hasPendingApply) {
            this.$message.warning('您有正在审批中的申请，请等待审核完成后再提交新的申请');
            return;
          }
          this.loading = true
          // 查找目标部门名称
          this.form.targetDeptName = this.findDeptNameById(this.form.targetDeptId)
          this.form.userId = this.user.userId

          // 根据是否存在ID判断是更新还是新增操作
          const submitMethod = this.form.id ? updateApply : deptTransferApi.submitApply
          const successMsg = this.form.id ? '申请修改成功' : '申请提交成功'
          this.form.status = 1

          // 提交申请到后端
          submitMethod(this.form).then(response => {
            this.loading = false
            this.$message.success(successMsg)
            this.resetForm()
            this.getApplyList() // 重新获取申请列表
          }).catch(error => {
            this.loading = false
            console.error('操作失败:', error)
            this.$message.error('操作失败，请稍后重试')
          })
        }
      })
    },
    getUser() {
        getUserProfile().then(response => {
            this.user = response.data;
            console.log(this.user)
            this.form.currentDeptId = this.user.dept.deptId
            this.form.currentDeptName = this.user.dept.deptName
            this.roleGroup = response.roleGroup;
            this.postGroup = response.postGroup;
            // 判断是否为管理员（根据角色组判断）
            this.isAdmin = this.roleGroup.includes('管理员');
        });
    },
    resetForm() {
      // 保存现有部门字段的值
      const currentDeptName = this.form.currentDeptName;
      const currentDeptId = this.form.currentDeptId;

      // 重置表单
      this.$refs.form.resetFields()

      // 恢复现有部门字段的值
      this.form.currentDeptName = currentDeptName;
      this.form.currentDeptId = currentDeptId;

      // 清除目标部门和ID
      // this.form.targetDeptId = ''
      this.form.targetDeptName = ''
      this.form.id = null // 清除ID，确保下次默认是新增操作
    },
    // 树形数据处理函数
    handleTree(data, id, parentId, children) {
      id = id || 'id'
      parentId = parentId || 'parentId'
      children = children || 'children'
      const result = []
      const hash = {}
      const len = data.length

      for (let i = 0; i < len; i++) {
        hash[data[i][id]] = data[i]
      }

      for (let j = 0; j < len; j++) {
        const current = data[j]
        const hashParent = hash[current[parentId]]
        if (hashParent) {
          !hashParent[children] && (hashParent[children] = [])
          hashParent[children].push(current)
        } else {
          result.push(current)
        }
      }
      return result
    },
    getStatusText(status) {
      const statusMap = {
        0: '申请中',
        1: '待审核',
        2: '审核通过',
        3: '审核驳回'
      }
      return statusMap[status] || '未知状态'
    },
    getStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'info',
        2: 'success',
        3: 'danger'
      }
      return typeMap[status] || 'default'
    },
      /** 修改按钮操作 */
      handleUpdate(row,type) {
          this.form = copyObj(row)
          this.form.status = type

          // 如果是驳回操作，弹出输入驳回原因的对话框
          if (type === 3) {
              this.$prompt('请输入驳回原因', '驳回申请', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  inputType: 'textarea',
                  inputPlaceholder: '请详细说明驳回原因',
                  inputValidator: (value) => {
                      if (!value || !value.trim()) {
                          return '驳回原因不能为空';
                      }
                      return true;
                  }
              }).then(({ value }) => {
                  this.form.reasons_rejection = value.trim();
                  this.submitUpdate();
              }).catch(() => {
                  // 取消驳回操作
                  this.$message('已取消驳回操作');
              });
          } else {
              // 直接提交通过操作
              this.submitUpdate();
          }
      },

      // 提交更新
      submitUpdate() {
          updateApply(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.getApplyList();
          }).catch(error => {
              console.error('操作失败:', error);
              this.$message.error('操作失败，请稍后重试');
          });
      },

      /** 删除按钮操作 */
       handleDelete(row) {
           const ids = row.id || this.ids;
           this.$modal.confirm('是否确认删除申请更换部门审批编号为"' + ids + '"的数据项？').then(() => {
               delApply(ids).then(response => {
                   this.$modal.msgSuccess("删除申请记录成功");
                   this.getApplyList();
               })
           }).catch(() => {
               // 取消删除操作
               this.$modal.msg("取消删除");
           });
       },

       /** 再次修改并重新提交申请 */
       handleModifyAndResubmit(row) {
           // 填充表单数据，保留原有的申请ID和信息
           this.form.id = row.id; // 保存原记录ID
           this.form.targetDeptId = row.targetDeptId;
           this.form.targetDeptName = row.targetDeptName;
           this.form.applyReason = row.applyReason;

           // 滚动到表单顶部，方便用户修改
           window.scrollTo({ top: 0, behavior: 'smooth' });

           // 提示用户可以修改信息后重新提交
           this.$message('请修改申请信息后重新提交');
       }



  }
}
</script>

<style scoped>
.mt-4 {
  margin-top: 20px;
}
</style>
